﻿using System;
using System.Collections.Generic;
using libtcod;

namespace RL
{

    public class InputEngine : IInputEngine
    {
        private Dictionary<TCODKeyCode, List<Action>> _keyListeners = new Dictionary<TCODKeyCode, List<Action>>();
        private Dictionary<TCODMouseCode, List<Action<TCODMouseData>>> _mouseListeners = new Dictionary<TCODMouseCode, List<Action<TCODMouseData>>>();
        public event Action<char> KeyPressed;
        private TCODKey _key;
        private TCODMouseData _mouse;
        public void Run()
        {
            _key = TCODConsole.checkForKeypress((int)TCODKeyStatus.KeyPressed);

            if (_key.Character != '\0')
                Logger.WriteInfo(string.Format("InputEngine: Key press ({0})", _key.Character));

            foreach (var listener in _keyListeners)
            {
                if (TCODConsole.isKeyPressed(listener.Key))
                    foreach (var action in listener.Value)
                    {
                        action.Invoke();
                    }
            }

            _mouse = TCODMouse.getStatus();
            if (_mouse.LeftButton)
            {
                _mouseListeners[TCODMouseCode.LeftButton].ForEach(x => x.Invoke(_mouse));
            }
            if (_mouse.RightButton)
            {
                _mouseListeners[TCODMouseCode.RightButton].ForEach(x => x.Invoke(_mouse));
            }
            if (_mouse.MiddleButton)
            {
                _mouseListeners[TCODMouseCode.MiddleButton].ForEach(x => x.Invoke(_mouse));
            }
            if (_mouse.PixelVelocityX != 0 || _mouse.PixelVelocityY != 0)
            {
                _mouseListeners[TCODMouseCode.Movement].ForEach(x => x.Invoke(_mouse));
            }
        }

        public void RegisterInterest(TCODMouseCode code, Action<TCODMouseData> act)
        {
            if (_mouseListeners.ContainsKey(code))
            {
                _mouseListeners[code].Add(act);
            }
            else
            {
                _mouseListeners.Add(code, new List<Action<TCODMouseData>> { act });
            }
        }
        public void RegisterInterest(TCODKeyCode code, Action act)
        {
            if (_keyListeners.ContainsKey(code))
            {
                _keyListeners[code].Add(act);
            }
            else
            {
                _keyListeners.Add(code, new List<Action> { act });
            }
        }
    }

    public enum TCODMouseCode
    {
        LeftButton,
        MiddleButton,
        RightButton,
        Wheel,
        Movement
    }
}